<!--
 * @Author: Cenven
 * @Date: 2021-05-18 09:59:09
 * @Description: 北京泓深教育发展有限公司
 * @Descripttion: 
 * @version: @Lastest
 * @LastEditTime: 2021-08-23 10:27:07
 * @CopyRight: 北京泓深教育发展有限公司
-->
<template>
  <div
    class="page-pc-custom-form"
    :style="customForm.dataJson && customForm.dataJson.config.customStyle"
  >
    <div class="custom-form-container" :style="{backgroundImage: bgImage ? 'url('+bgImage+')' : 'url()' }">
      <div class="form_name">{{ customForm.name }}</div>
      <div class="form_describe">{{ customForm.describe }}</div>
      <div v-if="sumbitState" class="aside">
        <Icon
          type="md-checkbox"
          size="200"
          color="#19be6b"
          class="show-animation"
        />
      </div>
      <!-- :style="{margin: '0 auto', width: formConfig.layout == 'vertical' ? '350px' : '600px',}" -->
      <div v-else>
        <Form
          :class="[formConfig.layout == 'vertical' ? 'form_top' : 'form_right']"
          ref="formEl"
          :model="customForm.dataJson"
          :label-position="formConfig.layout == 'vertical' ? 'top' : 'right'"
          :label-width="formConfig.layout == 'vertical' ? '' : 150"
          :style="{
            margin: '0 auto',
            width: formConfig.layout == 'vertical' ? '600px' : '600px'
          }"
        >
          <template v-for="(item, i) of createForm">
            <div :key="i" class="middle-form" v-if="!item.options.hidden">
              <FormItem
                :prop="'list.' + i + '.options.defaultValue'"
                v-if="item.type == 'input'"
                :label="item.label"
                :rules="item.rules"
              >
                <div class="form-item-size">
                  <Input
                    type="text"
                    v-model="customForm.dataJson.list[i].options.defaultValue"
                    :placeholder="item.options.placeholder"
                    :maxlength="item.options.maxLength"
                    :clearable="item.options.clearable"
                    :disabled="item.options.disabled"
                  >
                    <span slot="prepend" v-if="item.options.addonBefore">{{
                      item.options.addonBefore
                    }}</span>
                    <span slot="append" v-if="item.options.addonAfter">{{
                      item.options.addonAfter
                    }}</span>
                  </Input>
                </div>
              </FormItem>
              <FormItem
                :prop="'list.' + i + '.options.defaultValue'"
                :rules="item.rules"
                v-else-if="item.type == 'textarea'"
                :label="item.label"
              >
                <div class="form-item-size">
                  <Input
                    type="textarea"
                    v-model="customForm.dataJson.list[i].options.defaultValue"
                    :placeholder="item.options.placeholder"
                    :clearable="item.options.clearable"
                    :disabled="item.options.disabled"
                    :maxlength="item.options.maxLength"
                    :autosize="{
                      minRows: item.options.minRows,
                      maxRows: item.options.maxRows
                    }"
                  >
                  </Input>
                </div>
              </FormItem>
              <FormItem
                :prop="'list.' + i + '.options.defaultValue'"
                :rules="item.rules"
                v-else-if="item.type == 'number'"
                :label="item.label"
              >
                <InputNumber
                  style="width:350px;"
                  :placeholder="item.options.placeholder"
                  :disabled="item.options.disabled"
                  :max="item.options.max"
                  :min="item.options.min"
                  :step="item.options.step"
                  :precision="item.options.precision"
                  v-model="customForm.dataJson.list[i].options.defaultValue"
                ></InputNumber>
              </FormItem>
              <FormItem
                :prop="'list.' + i + '.options.defaultValue'"
                :rules="item.rules"
                v-else-if="item.type == 'select'"
                :label="item.label"
              >
                <div style="display: inline-block">
                  <Select
                    :placeholder="item.options.placeholder"
                    :clearable="item.options.clearable"
                    :disabled="item.options.disabled"
                    v-model="customForm.dataJson.list[i].options.defaultValue"
                    :multiple="item.options.multiple"
                    :filterable="item.options.showSearch"
                    style="width: 200px"
                  >
                    <Option
                      :value="el.value"
                      v-for="(el, j) of item.options.options"
                      :key="j"
                      >{{ el.label }}</Option
                    >
                  </Select>
                </div>
              </FormItem>
              <FormItem
                v-else-if="item.type == 'checkbox'"
                :label="item.label"
                :prop="'list.' + i + '.options.defaultValue'"
                :rules="item.rules"
              >
                <CheckboxGroup
                  :disabled="item.options.disabled"
                  v-model="customForm.dataJson.list[i].options.defaultValue"
                  :value="customForm.dataJson.list[i].options.defaultValue"
                >
                  <Checkbox
                    :label="el.value"
                    v-for="(el, j) of item.options.options"
                    :key="j"
                    >{{ el.label }}</Checkbox
                  >
                </CheckboxGroup>
              </FormItem>
              <FormItem
                :prop="'list.' + i + '.options.defaultValue'"
                :rules="item.rules"
                v-else-if="item.type == 'radio'"
                :label="item.label"
              >
                <RadioGroup
                  :disabled="item.options.disabled"
                  v-model="customForm.dataJson.list[i].options.defaultValue"
                  :value="customForm.dataJson.list[i].options.defaultValue"
                >
                  <Radio
                    :label="el.value"
                    v-for="(el, j) of item.options.options"
                    :key="j"
                    >{{ el.label }}</Radio
                  >
                </RadioGroup>
              </FormItem>
              <FormItem
                :prop="'list.' + i + '.options.defaultValue'"
                :rules="item.rules"
                v-else-if="
                  item.type == 'date' ||
                    item.type == 'daterange' ||
                    item.type == 'datetime'
                "
                :label="item.label"
              >
                <DatePicker
                  :type="item.type"
                  :placeholder="item.options.placeholder"
                  :value="item.options.defaultValue"
                  :disabled="item.options.disabled"
                  :clearable="item.options.clearable"
                  @on-change="
                    customForm.dataJson.list[i].options.defaultValue = $event
                  "
                ></DatePicker>
              </FormItem>
              <FormItem
                :prop="'list.' + i + '.options.defaultValue'"
                :rules="item.rules"
                v-else-if="item.type == 'time' || item.type == 'timerange'"
                :label="item.label"
              >
                <TimePicker
                  v-model="customForm.dataJson.list[i].options.defaultValue"
                  :type="item.type"
                  :placeholder="item.options.placeholder"
                  :value="item.options.defaultValue"
                  :format="item.options.format"
                  :disabled="item.options.disabled"
                  :clearable="item.options.clearable"
                ></TimePicker>
              </FormItem>
              <FormItem
                :prop="'list.' + i + '.options.defaultValue'"
                :rules="item.rules"
                v-else-if="item.type == 'switch'"
                :label="item.label"
              >
                <i-switch
                  :disabled="item.options.disabled"
                  v-model="customForm.dataJson.list[i].options.defaultValue"
                >
                  <span slot="open">开</span>
                  <span slot="close">关</span>
                </i-switch>
              </FormItem>
              <div v-else-if="item.type == 'button'" style="text-align: center">
                <Button
                  :disabled="item.options.disabled"
                  :type="item.options.type"
                  @click="submitForm('formEl', item.options.handle)"
                  >{{ item.label }}</Button
                >
              </div>
              <div v-else-if="item.type == 'text'" :style="item.options">
                {{ item.label }}
              </div>
              <Alert
                v-else-if="item.type == 'alert'"
                :type="item.options.type"
                :show-icon="item.options.showIcon"
                >{{ item.label }}</Alert
              >
            </div>
          </template>
        </Form>
      </div>
    </div>
  </div>
</template>
<script>
import { mapState, mapActions, mapMutations } from "vuex";
import { getCustomFormById, saveCustomFormResult } from "~/api/custom-form";
export default {
  name: "custom-form",
  components: {},
  data() {
    return {
      customForm: {},
      createForm: [],
      formConfig: {},
      sumbitState: false,
      bgImage:"",
    };
  },
  computed: {
    ...mapState({
      web_info(state) {
        return state.web_info;
      },
      kl_md(state) {
        return state.kl_md;
      }
    }),
    formId() {
      return this.$route.query.formId;
    }
  },
  created() {
    this.initPages();
  },
  activated() {
    this.initPages();
  },
  mounted() {},
  methods: {
    ...mapMutations(["SET_IS_LOADING"]),
    initPages() {
      this.getCustomForm();
    },
    async submitForm(submitForm, subType) {
      if (subType == "reset") {
        this.$refs[submitForm].resetFields();
        return;
      } else if (subType == "submit") {
        this.SET_IS_LOADING(true);
        this.$refs[submitForm].validate(async valid => {
          if (valid) {
            let form = {};
            this.customForm.dataJson.list.forEach(item => {
              if (
                item.type == "input" ||
                item.type == "textarea" ||
                item.type == "number" ||
                item.type == "select" ||
                item.type == "checkbox" ||
                item.type == "radio" ||
                item.type == "date" ||
                item.type == "time" ||
                item.type == "switch"
              ) {
                form[item.key] = item.options.defaultValue;
              }
            });
            let result = await saveCustomFormResult({
              formId: this.formId,
              dataJson: JSON.stringify(form)
            });
            if (result && result.data && result.data.code == 200) {
              this.$Message.success("提交成功");
              this.sumbitState = true;
            } else {
              this.$Message.error("提交失败");
            }
            // this.$refs[submitForm].resetFields();
          } else {
            this.$Message.error("校验未通过");
          }
        });
        this.SET_IS_LOADING(false);
      }
    },
    async getCustomForm() {
      this.SET_IS_LOADING(true);
      let result = await getCustomFormById(this.formId);
      if (result && result.data && result.data.code == 200) {
        if (result.data.data) {
          const { dataJson } = result.data.data;
          let json = dataJson ? JSON.parse(dataJson) : {};
          if(json && json.config && json.config.bgImageUrl){
              this.bgImage = json.config.bgImageUrl;
          }
          this.customForm = {
            ...result.data.data,
            dataJson: JSON.parse(dataJson)
          };
          this.createForm = JSON.parse(dataJson)["list"];
          this.formConfig = JSON.parse(dataJson)["config"];
          this.generateRules();
        }
        // this.customForm = result.data.data;
      } else {
        this.$Message.error("网络波动，请稍后重新进入！");
      }
      this.SET_IS_LOADING(false);
    },
    parseTime(time, pattern) {
      if (arguments.length === 0 || !time) {
        return null;
      }
      const format = pattern || "{y}-{m}-{d} {h}:{i}:{s}";
      let date;
      if (typeof time === "object") {
        date = time;
      } else {
        if (typeof time === "string" && /^[0-9]+$/.test(time)) {
          time = parseInt(time);
        } else if (typeof time === "string") {
          time = time.replace(new RegExp(/-/gm), "/");
        }
        if (typeof time === "number" && time.toString().length === 10) {
          time = time * 1000;
        }
        date = new Date(time);
      }
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
      };
      const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key];
        // Note: getDay() returns 0 on Sunday
        if (key === "a") {
          return ["日", "一", "二", "三", "四", "五", "六"][value];
        }
        if (result.length > 0 && value < 10) {
          value = "0" + value;
        }
        return value || 0;
      });
      return time_str;
    },
    generateRules() {
      this.createForm.forEach((el, i) => {
        if (el.rules && el.rules.length > 0) {
          el.rules.forEach((item, i) => {
            if (item.pattern) {
              item.pattern = eval(item.pattern);
            }
          });
        }
      });
    }
  }
};
</script>
<style lang="scss">
.page-pc-custom-form {
  .form_top {
    .ivu-form-item-label {
      text-align: left;
    }
  }
  .ivu-checkbox-group-item,
  .ivu-switch {
    display: block;
  }
  .ivu-radio-wrapper {
    display: block;
    white-space: pre-wrap;
  }
  .ivu-form-item-label {
    font-size: 15px;
    font-weight: bold;
    line-height: 18px;
  }
}
</style>
<style lang="scss" scoped>
.page-pc-custom-form {
  width: 100%;
  min-height: 100vh;
  background: #fff;
  
  .custom-form-container{
    width: 600px;
    height: 100%;
    padding: 20px;
    box-sizing: content-box;
    margin: 0 auto;
    background-repeat: no-repeat;
    background-size: 100% 100%;
    background-position: top;
    background-attachment: fixed;
  }
  .form_name {
    text-align: center;
    font-size: 26px;
    font-weight: bold;
    margin: 30px;
  }
  .form_describe {
    width: 600px;
    margin: 0 auto 20px;
    // margin-top: 20px;
    font-size: 16px;
    line-height: 1.5;
  }
  .aside {
    text-align: center;
    .show-animation {
      animation: showsuccess 1s;
    }

    @keyframes showsuccess {
      from {
        transform: scale(0.5, 0.5);
        -ms-transform: scale(0.5, 0.5);
        -webkit-transform: scale(0.5, 0.5);
      }
      to {
        transform: scale(1, 1);
        -ms-transform: scale(1, 1);
        -webkit-transform: scale(1, 1);
      }
    }

    @-webkit-keyframes showsuccess {
      from {
        transform: scale(0.5, 0.5);
        -ms-transform: scale(0.5, 0.5);
        -webkit-transform: scale(0.5, 0.5);
      }
      to {
        transform: scale(1, 1);
        -ms-transform: scale(1, 1);
        -webkit-transform: scale(1, 1);
      }
    }
  }
}
.middle-form {
  // padding: 2px 30%;
  .form-item-size {
    width: 350px;
    display: inline-block;
  }
  // /deep/ .ivu-form-item-error-tip {
  // left: 20%;
  // }
  // /deep/ .ivu-form-item-label{
  //   width: 100px;
  // }
}
</style>
